//
//  AboutMeViewController.m
//  Expressions
//
//  Created by admin on 3/10/13.
//  Copyright (c) 2013 admin. All rights reserved.
//

#import "AboutMeViewController.h"
#import "ExpressionUtils.h"
#import "ExpressionUtils.h"
@interface AboutMeViewController ()

@end

@implementation AboutMeViewController
@synthesize webView = _webView;
@synthesize banerView = _banerView;

-(void)showAlert:(NSString *)text
{
    UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Thông Báo" message:text delegate:nil cancelButtonTitle:nil otherButtonTitles:@"OK", nil];
    [alert show];
    [alert release];
}
-(void)displayMailComposerSheet
{
	MFMailComposeViewController *picker = [[MFMailComposeViewController alloc] init];
	picker.mailComposeDelegate = self;
	[picker setSubject:@""];
	// Set up recipients
	NSArray *toRecipients = [NSArray arrayWithObject:@"sinhchuong@yahoo.com"];
	NSArray *ccRecipients = [NSArray arrayWithObjects:@"", nil];
	NSArray *bccRecipients = [NSArray arrayWithObjects:@"",nil];
	
	[picker setToRecipients:toRecipients];
	[picker setCcRecipients:ccRecipients];
	[picker setBccRecipients:bccRecipients];
	
	// Fill out the email body text
	NSString *emailBody = @"";
	[picker setMessageBody:emailBody isHTML:NO];
	
	[self presentModalViewController:picker animated:YES];
	[picker release];
}

- (void)mailComposeController:(MFMailComposeViewController*)controller
          didFinishWithResult:(MFMailComposeResult)result error:(NSError*)error {
	
	NSString *feedbackMsg;
	// Notifies users about errors associated with the interface
	switch (result)
	{
		case MFMailComposeResultCancelled:
			feedbackMsg = @"Result: Mail sending canceled";
			break;
		case MFMailComposeResultSaved:
			feedbackMsg = @"Result: Mail saved";
			break;
		case MFMailComposeResultSent:
			feedbackMsg = @"Result: Mail sent";
			break;
		case MFMailComposeResultFailed:
			feedbackMsg = @"Result: Mail sending failed";
			break;
		default:
			feedbackMsg = @"Result: Mail not sent";
			break;
	}
    [self showAlert:feedbackMsg];
	[self dismissModalViewControllerAnimated:YES];
}

-(void)sentEmail
{
    Class mailClass = (NSClassFromString(@"MFMailComposeViewController"));
	if (mailClass != nil) {
		if ([mailClass canSendMail]) {
			[self displayMailComposerSheet];
		}
		else {
			// handle error
		}
	}
	else{
        // handle error
	}
}
-(void)tapGesture:(UITapGestureRecognizer *)gesture
{
    CGPoint point = [gesture locationInView:self.view];
    if (point.x > 71 && point.x < (71+ 153)) {
        if (point.y >(176 -22) && point.y < (176 +21 -22)) {
            [self sentEmail];
        }
    }
}
#pragma mark App Cycle
-(void)dealloc
{
    [_banerView release];
    [_webView release];
    [super dealloc];
}
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}
-(CGSize) caculatorSize:(CGSize )originSize destinationSize:(CGSize)destionationSize
{
    CGFloat w = 0;
    CGFloat h = 0;
    for (int  i = 0; i < destionationSize.width; i++) {
        CGFloat w1 = i;
        CGFloat h1 = (originSize.height *i)/originSize.width;
        if (h1 > destionationSize.height || h1 == destionationSize.height) {
            if (h1 == destionationSize.height) {
                w = w1;
                h = h1;
            }
            break;
        }
        w = w1;
        h = h1;
    }
    return CGSizeMake(w, h);
}
-(void)viewDidAppear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    UIImage *image = [UIImage imageNamed:@"Background_About"];
    if (self.view.frame.size.height > 500 || self.view.frame.size.width > 500) {
        image = [UIImage imageNamed:@"Background_About_ip5"];
    }
    CGSize sizeDes = [self caculatorSize:image.size destinationSize:CGSizeMake(self.webView.frame.size.width, self.webView.frame.size.height)];
    image = [ExpressionUtils resizeImage:image destinationSize:sizeDes];
    self.view.backgroundColor = [UIColor colorWithPatternImage:image];

    
}
- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.

    UITapGestureRecognizer *gesture = [[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapGesture:)]autorelease];
    [self.view addGestureRecognizer:gesture];
    self.webView.backgroundColor = [UIColor clearColor];
    self.webView.opaque = NO;
    NSString *html = @"";
    html = @"<div style =\"padding-top:10px;padding-left:20px;padding-right:20px;\" align = \"letf\">";
    html = [html stringByAppendingString:@"<h4 align = \"center\">Công thức Toán học Lite 1.0</h4>"];
    html = [html stringByAppendingString:@"<p align = \"left\">Copyright 2012 by Tam Sao Corporation, Sysney, Australia.</br>All rights reserved</p>"];
//    html = [html stringByAppendingString:@"</br>"];
    html = [html stringByAppendingString:@"<p>Tác giả: Nguyễn Sinh Chương(John)</p>"];
    html = [html stringByAppendingString:@"<div align =\"center\"><a href = \"sendmail\">sinhchuong@yahoo.com</a></div>"];
    html = [html stringByAppendingString:@"Các phần mềm cho điện thoại tiếp theo : Công thức vật lý, Công thức Hoá học. Mọi phản hồi xin gửi email  về địa chỉ trên.</br>"];
    html = [html stringByAppendingString:@"Xin chân thành cảm ơn sự ủng hộ(bằng cách click banner quảng cáo và tải bản full với đầy đủ công thức cần thiết dùng cho học tập và làm việc). </br>"];
    html = [html stringByAppendingString:@""];
    html = [html stringByAppendingString:@""];
    html = [html stringByAppendingString:@""];
    html = [html stringByAppendingString:@""];
    html = [html stringByAppendingString:@"</div>"];
//    html = [html stringByAppendingString:@"</body>"];
    [_webView loadHTMLString:html baseURL:nil];
    
    
    
    self.banerView = [[[ADBannerView alloc]initWithFrame:CGRectMake(0, 460-50, _banerView.frame.size.width, _banerView.frame.size.height)]autorelease];
    
    _banerView.delegate =  self;
    _banerView.autoresizingMask = UIViewAutoresizingFlexibleTopMargin ;
    if ([ExpressionUtils isLandscapse]) {
        _banerView.currentContentSizeIdentifier = ADBannerContentSizeIdentifierLandscape;
    }else{
        _banerView.currentContentSizeIdentifier = ADBannerContentSizeIdentifierPortrait;
    }
    CGRect  rect = _banerView.frame;
    rect.origin.x = (self.view.frame.size.width - _banerView.frame.size.width)/2;
    rect.origin.y = self.view.frame.size.height - _banerView.frame.size.height;
    _banerView.frame = rect;
    [self.view addSubview:_banerView];
    [self.view bringSubviewToFront:_banerView];
    _banerView.hidden = YES;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
-(BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
    NSString *urlString = request.URL.absoluteString;
    if ([urlString rangeOfString:@"sendmail"].length > 0) {
        [self sentEmail];
    }
    return YES;
}
-(BOOL)shouldAutorotate
{
    return YES;
}
-(BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation
{
    return YES;
}
-(void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation
{
    if (_banerView) {
        if ([ExpressionUtils isLandscapse]) {
            _banerView.currentContentSizeIdentifier = ADBannerContentSizeIdentifierLandscape;
        }else{
            _banerView.currentContentSizeIdentifier = ADBannerContentSizeIdentifierPortrait;
        }
        CGRect  rect = _banerView.frame;
        rect.origin.x = (self.view.frame.size.width - _banerView.frame.size.width)/2;
        rect.origin.y = self.view.frame.size.height - _banerView.frame.size.height;
        _banerView.frame = rect;
        
    }
}
#pragma mark -
#pragma mark - AdBanerView Method
- (void)bannerViewDidLoadAd:(ADBannerView *)banner
{
    _banerView.hidden = NO;
    CGRect  rect = _banerView.frame;
    rect.origin.x = (self.view.frame.size.width - _banerView.frame.size.width)/2;
    rect.origin.y = self.view.frame.size.height - _banerView.frame.size.height;
    _banerView.frame = rect;
    
    rect = self.webView.frame;
    if ((rect.size.height + _banerView.frame.size.height) > self.view.frame.size.height) {
        rect.size.height -= _banerView.frame.size.height;
    }
    
    self.webView.frame = rect;
}
- (void)bannerView:(ADBannerView *)banner didFailToReceiveAdWithError:(NSError *)error
{
    _banerView.hidden = YES;
    CGRect  rect ;
    rect = self.webView.frame;
    rect.size.height = self.view.frame.size.height;
    self.webView.frame = rect;
}

@end
